/*
 * File:   Configuration.cpp
 * Author: wilq
 *
 * Created on June 8, 2012, 2:00 PM
 */

#include "Configuration.h"
#include "Log.h"
#include <boost/filesystem/path.hpp>
#include <boost/property_tree/xml_parser.hpp>

inline bool FileExists(const std::string &file)
{
	FILE* f = fopen(file.c_str(), "r");
	if (NULL == f)
	{
		return false;
	}
	fclose(f);
	return true;
}

Configuration::Configuration(const std::string &dir, const std::string &name) : readed(false)
{
		std::string m_dir(dir);
		if (!m_dir.empty())
		{
			boost::filesystem::path slash("/");
			if ((m_dir[m_dir.size()-1]!='\\') && (m_dir[m_dir.size()-1]!='/'))
					m_dir += slash.make_preferred().native();
		}

		if (!readed && (name.find(".xml")!=std::string::npos || name.find(".XML")!=std::string::npos) && FileExists(m_dir+name))
		{
			printf("INFO: Found .xml log file - %s, trying to read configuration\n", (m_dir+name).c_str());
			try{
				boost::property_tree::xml_parser::read_xml(m_dir+name, pt);
				m_file = m_dir+name;
				readed = true;
				printf("INFO: Configuration loaded from - %s\n", (m_dir+name).c_str());
			} catch(const boost::property_tree::xml_parser::xml_parser_error &e)
			{
				printf("ERROR: Error durring loading a configuration from XML file - %s:%d, %s, file ignored\n", e.filename().c_str(), e.line(), e.message().c_str());
			}
		}

		if (!readed && FileExists(m_dir+name+".xml"))
		{
			printf("INFO: Found .xml log file - %s, trying to read configuration\n", (m_dir+name+".xml").c_str());
			try{
				boost::property_tree::xml_parser::read_xml(m_dir+name+".xml", pt);
				m_file = m_dir+name+".xml";
				readed = true;
				printf("INFO: Configuration loaded from - %s\n", (m_dir+name+".xml").c_str());
			} catch(const boost::property_tree::xml_parser::xml_parser_error &e)
			{
				printf("ERROR: Error durring loading a configuration from XML file - %s:%d, %s, file ignored\n", e.filename().c_str(), e.line(), e.message().c_str());
			}
		}

		if (!readed && FileExists(m_dir+name+".XML"))
		{
			printf("INFO: Found .XML log file - %s, trying to read configuration\n", (m_dir+name+".XML").c_str());
			try{
				boost::property_tree::xml_parser::read_xml(m_dir+name+".XML", pt);
				m_file = m_dir+name+".XML";
				readed = true;
				printf("INFO: Configuration loaded from - %s\n", (m_dir+name+".XML").c_str());
			} catch(const boost::property_tree::xml_parser::xml_parser_error &e)
			{
				printf("ERROR: Error durring loading a configuration from XML file - %s:%d, %s, file ignored\n", e.filename().c_str(), e.line(), e.message().c_str());
			}
		}
}


